package edu.spec.sys.controller;

import edu.spec.sys.model.Command;
import edu.spec.sys.model.Module;
import edu.spec.sys.model.Role;
import edu.spec.sys.model.User;
import edu.spec.sys.model.dto.MvcReturn;
import edu.spec.sys.service.iface.ICommandService;
import edu.spec.sys.service.iface.IModuleService;
import edu.spec.sys.service.iface.IRoleService;
import edu.spec.sys.service.iface.IUserService;
import edu.spec.sys.web.SessionContext;
import org.madgecko.basic.util.SecurityUtil;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.ResponseBody;

import javax.inject.Inject;
import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpSession;
import java.security.NoSuchAlgorithmException;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;


@Controller
@RequestMapping("/admin")
public class AdminLoginController {

    @Inject
    private IUserService userService;
    @Inject
    private IRoleService roleService;
    @Inject
    private IModuleService moduleService;
    @Inject
    private ICommandService commandService;

    @RequestMapping(value = "/login", method = RequestMethod.GET)
    public String login(){
        return "admin/login";
    }

    @ResponseBody
    @RequestMapping(value = "/login", method = RequestMethod.POST)
    public Object login(String username, String pwd, HttpSession session, HttpServletRequest request){
        try {
            // 获取username相同的user
            User u = userService.loadByName(username);
            if(u==null){
                return new MvcReturn(false, null, "用户名不存在");
            }
            // 验证密码
            String pagePwd = SecurityUtil.md5(pwd);
            if(!u.getPassword().equals(pagePwd)){
                return new MvcReturn(false, null, "用户名或密码错误");
            }
            // 为当前会话session存入属性user
            session.setAttribute("user", u);
            String sid = null;
            Cookie[] cookies = request.getCookies();
            for (Cookie c : cookies){
                if ("JSESSIONID".equals(c.getName())){
                    sid = c.getValue();
                }
            }
            session.setAttribute("JSESSIONID", sid);
            System.out.println("serverSid:"+ sid);
            return new MvcReturn(true);
        } catch (NoSuchAlgorithmException e) {
            e.printStackTrace();
            return new MvcReturn(false);
        }
    }

    @ResponseBody
    @RequestMapping("/initAdminAuthority")
    public Object initTeacherAuthority(HttpSession session){
        User currentUser = (User)session.getAttribute("user");
        Map<String, Object> authorityMap = new HashMap<String, Object>();
        authorityMap.put("user", currentUser);
        if(currentUser.getUsername().equals("root")){
            //root user init
            authorityMap.put("userModule", moduleService.listAllModule());
            authorityMap.put("userCommand", commandService.listAllCommand());
        }else{
            //normal user init
            List<Role> roles = roleService.listRoleByUser(currentUser.getId());
            List<Integer> roleIds = new ArrayList<Integer>();
            for(Role r : roles){
                roleIds.add(r.getId());
            }
            List<Command> commands = commandService.listCommandByRoles(roleIds);
            List<Module> modules = moduleService.listModuleByRoles(roleIds);
//            CommandContext.addUserCommand(session.getId(), convertCommands2Str(commands));
            SessionContext.addSession(session);
            authorityMap.put("userModule", modules);
            authorityMap.put("userCommand", commands);
        }
        // 不将initTeacherAuthority的工作放入login方法的原因是，login方法返回登录结果、不能直接返回权限，
        // 若将authorityMap存入用户的session,则占用内存较多，
        // 采用2次请求，第一次请求返回登录结果，第二次请求返回用户权限。
        return new MvcReturn(true, authorityMap);
    }

    @RequestMapping("/logout")
    public String logout(HttpSession session){
        SessionContext.removeSession(session.getId());
//        CommandContext.removeUserCommand(session.getId());
        session.invalidate();
        return "redirect:/admin/login";
    }

    private String convertCommands2Str(List<Command> commands){
        String str = "|";
        for(Command c : commands){
            str += c.getUrl() + "|";
        }
        return str;
    }

	@RequestMapping("")
	public String admin(){
        return "admin/index";
	}

    @RequestMapping("/header")
    public String header(){
        return "admin/header";
    }

//    @RequestMapping(value = "/studentLogin", method = RequestMethod.GET)
//    public String stuLogin(){
//        return "studentLogin";
//    }

//    @RequestMapping(value = "/studentLogin", method = RequestMethod.POST)
//    public Object stuLogin(String stuNum, String pwd,  HttpSession session){
//        try {
//            Student stu = studentService.loadByStuNum(stuNum);
//            if(stu==null){
//                return new MvcReturn(false, null, "用户名不存在");
//            }
//            // 验证密码
//            String pagePwd = SecurityUtil.md5(pwd);
//            if(!stu.getPassword().equals(pagePwd)){
//                return new MvcReturn(false, null, "用户名或密码错误");
//            }
//            // 为当前会话session存入属性user
//            session.setAttribute("stu", stu);
//            return new MvcReturn(true);
//        } catch (NoSuchAlgorithmException e) {
//            e.printStackTrace();
//            return new MvcReturn(false);
//        }
//    }
}
